<template>
  <div v-if="showStatusBar" class="statusBarBox">
    <div class="row justify-between items-center">
      <div class="col-auto">
        工人：{{ wName }} <br />
        工人记录时间： {{ wTime }} <br/>
        工单状态:   <q-chip v-if="orderStatus" square :color="orderStatus==='完成'?'green':'red'" text-color="white">
           {{ orderStatus }}
      </q-chip>
      </div>
      <div v-show="flow" class="col-auto cur-flow">
          {{ flow }}
      </div>
      <div class="col-auto" v-if="orderStatus==='完成'">
        完成时间：{{ getPfTime() }}
      </div>
      <div class="col-auto" v-else>
        持有者 ：{{ hName }} <br />
        更新时间：{{ hTime }}
      </div>
    </div>
    <div
      v-if="role === 'QC' && showReviewBox"
      class="row justify-between items-center qcReviewBox"
    >
      <div class="col-auto col-sm-auto resetBtnBox">
        <q-btn
          v-show="allowReset"
          push
          color="grey-8"
          class="woItemBtn"
          label="重设审核结果"
          :disable="userStore.currentDept.source !== woDetailsStore.orderInfo.source_code"
          @click="confirmReset = true"
        />
      </div>
      <div class="col-5 col-sm-4 reviewBtnBox">
        <q-btn-toggle
          v-model="reviewResult"
          spread
          dense
          no-caps
          toggle-color="deep-purple-8"
          color="white"
          text-color="black"
          :options="[
            { label: '不合格', value: 'fail' },
            { label: '合格', value: 'pass' },
          ]"
          class="reviewBtn"
          :disable="!editable"
          @update:model-value="submitResult()"
        />
      </div>
    </div>
    <div
      v-else-if="role === 'QC' && !showReviewBox && showStartBtn"
      class="row items-center justify-end qcReviewBox"
    >
      <span class="col-12 col-sm-2 infoSpan">
        <q-btn
          label="开始"
          color="indigo-3"
          class="startBtn"
          @click="startReview()"
          :disable="userStore.currentDept.source !== woDetailsStore.orderInfo.source_code || !editable"
        />
      </span>
    </div>
  </div>
  <div v-else>
    <p>ERROR: Cannot get role.</p>
  </div>

  <q-dialog v-model="confirmReset">
    <q-card>
      <q-card-section
        class="bg-deep-purple-9 text-white row items-center justify-center"
      >
        <div class="text-h6 f-bold">重设审核结果</div>
      </q-card-section>
      <q-card-section class="row items-center">
        <span>审核结果和时间将会删除，确定重设审核结果?</span>
      </q-card-section>

      <q-card-actions align="center">
        <q-btn label="取消" color="grey-6" v-close-popup />
        <q-btn
          label="确定"
          color="deep-purple-6"
          v-close-popup
          @click="resetWOReview()"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>

  <q-dialog v-model="confirmResetPass">
    <q-card>
      <q-card-section
        class="bg-deep-purple-9 text-white row items-center justify-center"
      >
        <div class="text-h6 f-bold">重设审核结果</div>
      </q-card-section>
      <q-card-section class="row items-center">
        <span>审核结果和时间将会被更新，确定重设审核结果?</span>
      </q-card-section>

      <q-card-actions align="center">
        <q-btn label="取消" color="grey-6" v-close-popup />
        <q-btn
          label="确定"
          color="deep-purple-6"
          v-close-popup
          @click="submitResult()"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { useRouter } from "vue-router";
import { useQuasar } from "quasar";
import { useUserStore } from "src/stores/modules/userStore";
import { useWoDetailsStore } from "src/stores/modules/wodetailsStore";
import { useWOReviewStore } from "src/stores/modules/woReviewStore";
import { ref } from "vue";

const userStore = useUserStore();
const $router = useRouter();
const $q = useQuasar();
const woReviewStore = useWOReviewStore();
const woDetailsStore = useWoDetailsStore();
const routingHistory = woDetailsStore.routingHistory;
let role = null;
let accID = null;
let orderNo = ref(null);
let allowReset = ref(false);
const editable = ref(false);
const wName = ref(null);
const wTime = ref(null);
const hName = ref(null);
const hTime = ref(null);
const flow = ref(null);
const showStatusBar = ref(false);
const showReviewBox = ref(false);
const showStartBtn = ref(null);
const orderStatus = ref(null)
// QC: value of review WO
const reviewResult = ref(null);
// QC: Confirm reset WO review modal box
const confirmReset = ref(false);
const confirmResetPass = ref(false);

// QC: Switch tab if pressed fail
const emit = defineEmits(["switchTab"]);
// emit('switchTab')

// Initialize
const initStatusBar = () => {
  console.log("initstatusbar");
  role = userStore.currentDept ? userStore.currentDept.roleGroup : null;
  accID = userStore.currentDept.accID ? userStore.currentDept.accID : null;
  orderNo.value = woDetailsStore.getOrderNo ? woDetailsStore.getOrderNo : null;
  console.log("orderNo in status bar: ", orderNo.value);
  // Get status Bar info
  wName.value = woDetailsStore.statusInfo.worker_name
    ? woDetailsStore.statusInfo.worker_name
    : "未有纪录";
  wTime.value = woDetailsStore.statusInfo.worker_record_time
    ? woDetailsStore.statusInfo.worker_record_time
    : "未有纪录";
  hName.value = woDetailsStore.statusInfo.holder_name
    ? woDetailsStore.statusInfo.holder_name
    : "未有纪录";
  hTime.value = woDetailsStore.statusInfo.holder_record_time
    ? woDetailsStore.statusInfo.holder_record_time
    : "未有纪录";
  flow.value = woDetailsStore.statusInfo.flow
    ? woDetailsStore.statusInfo.flow
    : "";
  orderStatus.value = woDetailsStore.statusInfo.order_status
    ? woDetailsStore.statusInfo.order_status
    : "";
  showStatusBar.value = true;

  // Get QC Current Status
  if (role === "QC") {
    editable.value = woReviewStore.editable;
    if (woReviewStore.currentStatus !== null) {
      // started
      showReviewBox.value = true;
    } else {
      // not started
      showStartBtn.value = true;
    }
    console.log("showReviewBox: ", showReviewBox.value);
    console.log("showStartBtn", showStartBtn.value);
    // get review result
    reviewResult.value = woReviewStore.result;
    allowReset.value = woReviewStore.allow_reset;
    console.log("allowReset: ", allowReset.value);
  } else {
    showReviewBox.value = false;
  }
};
initStatusBar();

// QC: Start Work Order Review (if currentStatus==='null)
const startReview = () => {
  // call api to start review
  woReviewStore.qcUpdateWOReview(
    accID,
    orderNo.value,
    null,
    null,
    null,
    "start"
  );
  woReviewStore.setCurrentStatus("start");
  showReviewBox.value = true;
  showStartBtn.value = false;
};

// QC: submitResult
const submitResult = async () => {
  // get reviewResult
  console.log("result changed: ", reviewResult.value);
  // if = pass submit sth
  if (reviewResult.value === "pass") {
    if (woReviewStore.currentStatus === "complete" && !confirmResetPass.value) {
      // pop alert box
      confirmResetPass.value = true;
    } else {
      // call api
      const res = await woReviewStore.qcUpdateWOReview(
        accID,
        orderNo.value,
        null,
        null,
        false,
        "complete"
      );
      if (res) {
        woReviewStore.setCurrentStatus("complete");
        woReviewStore.setReviewResult("pass");
        editable.value = false
        woReviewStore.editable = false
        allowReset.value = true
      } else {
        // alert
        console.log("cannot set review");
      }
    }
  } else {
    woReviewStore.setReviewResult("fail");
    console.log("route to woReview Page");
    emit("switchTab");
  }
};

// QC: Reset WO review
const resetWOReview = async () => {
  reviewResult.value = "";
  const res = await woReviewStore.initWOReview(
    accID,
    orderNo.value,
    null,
    null,
    "init"
  );

  if (res) {
    $q.notify({
      type: "positive",
      textColor: "white",
      message: "成功重置审核结果!",
      timeout: 2000,
      position: "center",
    });
      allowReset.value = false
      editable.value = true
  } else {
    $q.notify({
      type: "negative",
      textColor: "white",
      message: "错误发生 !",
      timeout: 2000,
      position: "center",
    });
  }
  // call wodetails again
  //   woReviewStore.setCurrentStatus('start')
};

function getPfTime() {
  const pf = routingHistory.find(i=>i.flow=='PF')
  return pf.dispatchName_endDate
}


</script>

<style lang="scss" scoped>
.statusBarBox {
  margin: 10px 5px 0px 5px;
  width: 100%;
  background-color: rgba(255, 255, 255, 0.801);
  border-radius: 5px;
  padding: 5px 10px 5px 10px;
  font-size: 1rem;
  @media (max-width: 480px) {
    font-size: 0.8rem;
    margin: 0px 0px 0px 0px;
  }
  .cur-flow {
    background-color: #4436d0;
    padding: 10px 10px 10px 10px;
    border-radius: 10px;
    color: white;
  }
  .qcReviewBox {
    margin-top: 10px;
    margin-bottom: 5px;
    .startBtn {
      width: 100%;
    }
    .infoSpan {
      font-weight: bold;
      font-size: 1.2rem;
      @media (max-width: 480px) {
        font-size: 0.9rem !important;
      }
    }
  }
}
</style>
